<template>
  <div id="panel">
    <!-- 搜索表单区域 -->
    <el-card class="queryForm">
      <el-form
        ref="queryForm"
        :model="queryParams"
        :inline="true"
        :label-position="'right'"
      >
        <el-form-item label="物资名称：" prop="materialName">
          <el-input
            v-model="queryParams.materialName"
            placeholder="请输入物资名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="物资分类：" prop="materialType">
          <el-select
            v-model="queryParams.materialType"
            placeholder="请选择物资分类"
          >
            <el-option label="环境监测" value="环境监测"></el-option>
            <el-option label="污染物控制" value="污染物控制"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格型号：" prop="specModel">
          <el-input
            v-model="queryParams.specModel"
            placeholder="请输入规格型号"
          ></el-input>
        </el-form-item>
        <el-form-item label="批次编号：" prop="batchNo">
          <el-input
            v-model="queryParams.batchNo"
            placeholder="请输入批次编号"
          ></el-input>
        </el-form-item>
        <div class="searchBtnBox">
          <el-button type="primary" icon="el-icon-search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button @click="resetQuery">重置</el-button>
        </div>
      </el-form>
    </el-card>

    <!-- 操作按钮和表格区域 -->
    <el-card class="pageContent">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            >导出</el-button
          ></el-col
        >
      </el-row>
      <el-table
        :data="tableData"
        stripe
        :height="tableHeight"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="materialName" label="物资名称" />
        <el-table-column prop="materialType" label="物资分类" />
        <el-table-column prop="specModel" label="规格型号" />
        <el-table-column prop="batchNo" label="批次编号" />
        <el-table-column prop="stock" label="库存" />
        <el-table-column prop="riskSource" label="风险源" />
        <el-table-column fixed="right" label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="view(scope.row)">详情</el-button>
            <el-button type="text" @click="edit(scope.row)">修改</el-button>
            <el-button type="text" @click="delRows(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination-self"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :pager-count="5"
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        layout="slot, total, sizes, prev, pager, next, jumper"
        :total="tableList.total"
      >
        <el-button
          class="refresh-button"
          icon="el-icon-refresh"
          title="刷新"
          @click="getList"
        />
      </el-pagination>
    </el-card>

    <!-- 新增/修改弹框（应急物资装备适配） -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物资名称" prop="materialName" required>
              <el-input
                v-model="form.materialName"
                placeholder="请输入物资名称"
              />
            </el-form-item>
            <el-form-item label="物资分类" prop="materialType" required>
              <el-select
                v-model="form.materialType"
                placeholder="请选择物资分类"
              >
                <el-option label="环境监测" value="环境监测"></el-option>
                <el-option label="污染物控制" value="污染物控制"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="库存" prop="stock" required>
              <el-input-number
                v-model="form.stock"
                :min="0"
                placeholder="请输入库存"
              />
            </el-form-item>
            <el-form-item label="批次编号" prop="batchNo">
              <el-input v-model="form.batchNo" placeholder="请输入批次编号" />
            </el-form-item>
            <el-form-item label="风险源" prop="riskSource" required>
              <el-select v-model="form.riskSource" placeholder="请选择风险源">
                <el-option
                  label="中金嵩县嵩原黄金冶炼有限责任公司"
                  value="中金嵩县嵩原黄金冶炼有限责任公司"
                ></el-option>
                <!-- 可补充其他风险源选项 -->
              </el-select>
            </el-form-item>
            <el-form-item label="物资缩略图" prop="thumbnail">
              <el-upload
                action="/api/upload"
                :limit="1"
                accept=".png,.jpg,.jpeg"
                :file-size="10 * 1024 * 1024"
                :on-error="handleUploadError"
                :on-success="handleThumbnailSuccess"
                :before-upload="beforeThumbnailUpload"
                :show-file-list="true"
                class="upload-demo"
              >
                <div class="upload-plus">
                  <i class="el-icon-plus"></i>
                </div>
                <div slot="tip" class="el-upload__tip">
                  请上传大小不超过10MB、格式为png/jpg/jpeg的文件
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item label="技术手册" prop="techManual">
              <el-upload
                action="/api/upload"
                :limit="1"
                accept=".doc,.docx,.pdf"
                :file-size="50 * 1024 * 1024"
                :on-error="handleUploadError"
                :on-success="handleManualSuccess"
                :before-upload="beforeManualUpload"
                :show-file-list="true"
                class="upload-demo"
              >
                <el-button size="small" type="primary">选取文件</el-button>
                <div slot="tip" class="el-upload__tip">
                  请上传大小不超过50MB、格式为doc/pdf的文件
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经办人" prop="handler">
              <el-input v-model="form.handler" placeholder="请输入经办人" />
            </el-form-item>
            <el-form-item label="规格型号" prop="specModel">
              <el-input v-model="form.specModel" placeholder="请输入规格型号" />
            </el-form-item>
            <el-form-item label="物资单位" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入物资单位" />
            </el-form-item>
            <el-form-item label="进仓时间" prop="warehouseTime">
              <el-date-picker
                v-model="form.warehouseTime"
                type="date"
                placeholder="选择进仓时间"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "EmergencyMaterials",
  components: {},
  data() {
    return {
      tableHeight: window.innerHeight - 400,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialName: "", // 物资名称
        materialType: "", // 物资分类
        specModel: "", // 规格型号
        batchNo: "", // 批次编号
      },
      tableList: {
        total: 0,
        rows: [],
      },
      ids: [], // 选中项ID集合
      tableData: [
        {
          id: "1",
          materialName: "气体检测器",
          materialType: "环境监测",
          specModel: "",
          batchNo: "",
          stock: "1个",
          riskSource: "中金嵩县嵩原黄金冶炼有限责任公司",
          remark: "",
        },
        {
          id: "2",
          materialName: "漂白粉",
          materialType: "污染物控制",
          specModel: "",
          batchNo: "",
          stock: "1t",
          riskSource: "中金嵩县嵩原黄金冶炼有限责任公司",
          remark: "",
        },
        {
          id: "3",
          materialName: "堵漏材料及工具",
          materialType: "污染物控制",
          specModel: "",
          batchNo: "",
          stock: "100个",
          riskSource: "中金嵩县嵩原黄金冶炼有限责任公司",
          remark: "",
        },
      ],
      open: false, // 弹框显隐
      title: "", // 弹框标题
      form: {
        id: "",
        materialName: "",
        materialType: "",
        stock: 0,
        batchNo: "",
        riskSource: "",
        thumbnail: "",
        techManual: "",
        handler: "",
        specModel: "",
        unit: "",
        warehouseTime: "",
        remark: "",
      },
      rules: {
        materialName: [
          { required: true, message: "物资名称不能为空", trigger: "blur" },
        ],
        materialType: [
          { required: true, message: "物资分类不能为空", trigger: "change" },
        ],
        stock: [
          { required: true, message: "库存不能为空", trigger: "blur" },
          { type: "number", message: "请输入有效数字", trigger: "blur" },
        ],
        riskSource: [
          { required: true, message: "风险源不能为空", trigger: "change" },
        ],
      },
    };
  },
  mounted() {
    this.pageInit();
  },
  methods: {
    pageInit() {
      this.getList();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加应急物资装备";
    },
    handleUpdate() {
      if (this.ids.length === 0) {
        this.$message.warning("请先勾选需要修改的数据");
        return;
      }
      if (this.ids.length > 1) {
        this.$message.warning("只能选择一条数据进行修改");
        return;
      }
      const row = this.tableData.find((item) => item.id === this.ids[0]);
      this.reset();
      this.open = true;
      this.title = "修改应急物资装备";
      this.form = {
        ...row,
        stock: parseInt(row.stock) || 0, // 提取数字部分
      };
    },
    handleDelete() {
      if (this.ids.length === 0) {
        this.$message.warning("请先勾选需要删除的数据");
        return;
      }
      const names = this.tableData
        .filter((item) => this.ids.includes(item.id))
        .map((item) => item.materialName)
        .join("、");
      this.$confirm(`是否确认删除以下物资：${names}`, "删除确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.tableData = this.tableData.filter(
            (item) => !this.ids.includes(item.id)
          );
          this.ids = [];
          this.getList();
          this.$message.success("删除成功");
        })
        .catch(() => {});
    },
    view(row) {
      console.log("查看详情", row);
    },
    edit(row) {
      this.reset();
      this.open = true;
      this.title = "修改应急物资装备";
      this.form = {
        ...row,
        stock: parseInt(row.stock) || 0,
      };
    },
    delRows(row) {
      this.$confirm(`是否确认删除物资：${row.materialName}`, "删除确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.tableData = this.tableData.filter((item) => item.id !== row.id);
          this.getList();
          this.$message.success("删除成功");
        })
        .catch(() => {});
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.getList();
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: "",
        materialName: "",
        materialType: "",
        stock: 0,
        batchNo: "",
        riskSource: "",
        thumbnail: "",
        techManual: "",
        handler: "",
        specModel: "",
        unit: "",
        warehouseTime: "",
        remark: "",
      };
      this.$refs.form && this.$refs.form.resetFields();
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 处理库存显示格式（数字+单位）
          const submitData = {
            ...this.form,
            stock: this.form.unit
              ? `${this.form.stock}${this.form.unit}`
              : `${this.form.stock}`,
          };

          if (this.form.id) {
            // 修改操作
            const index = this.tableData.findIndex(
              (item) => item.id === this.form.id
            );
            this.tableData.splice(index, 1, submitData);
            this.$message.success("修改成功");
          } else {
            // 新增操作
            submitData.id = Date.now().toString();
            this.tableData.unshift(submitData);
            this.$message.success("新增成功");
          }
          this.open = false;
          this.getList();
        }
      });
    },
    handleExport() {
      this.$message.success("导出功能待实现");
    },
    getList() {
      this.tableList.total = this.tableData.length;
      this.tableList.rows = this.tableData;
    },
    // 缩略图上传校验
    beforeThumbnailUpload(file) {
      const isImage = file.type.startsWith("image/");
      const isSize = file.size / 1024 / 1024 <= 10;
      if (!isImage) {
        this.$message.error("仅支持上传图片格式文件（png/jpg/jpeg）");
        return false;
      }
      if (!isSize) {
        this.$message.error("文件大小不能超过 10MB");
        return false;
      }
      return true;
    },
    handleThumbnailSuccess(response, file) {
      this.form.thumbnail = response.filePath;
      this.$message.success("物资缩略图上传成功");
    },
    // 技术手册上传校验
    beforeManualUpload(file) {
      const isDoc =
        file.type === "application/msword" ||
        file.type ===
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
        file.type === "application/pdf";
      const isSize = file.size / 1024 / 1024 <= 50;
      if (!isDoc) {
        this.$message.error("仅支持上传 doc/docx/pdf 格式的文件");
        return false;
      }
      if (!isSize) {
        this.$message.error("文件大小不能超过 50MB");
        return false;
      }
      return true;
    },
    handleManualSuccess(response, file) {
      this.form.techManual = response.filePath;
      this.$message.success("技术手册上传成功");
    },
    handleUploadError() {
      this.$message.error("文件上传失败，请重试");
    },
  },
};
</script>

<style lang="scss" scoped>
p {
  margin: 0;
}

img {
  vertical-align: middle;
}

#panel {
  padding-bottom: 40px;
  min-height: calc(100% - 20px);
  margin: 0;

  .pagination-self {
    margin: 20px 0;
    display: flex;
    justify-content: flex-end;
    position: relative;

    .el-pagination__total {
      position: absolute;
      left: 5px;
      color: #409eff;
      font-weight: 600;
      font-size: 15px;
    }
  }

  .refresh-button {
    .el-icon-refresh {
      font-size: 18px;
      line-height: 28px;
    }
  }

  .el-card {
    margin: 10px;
  }

  .queryForm .el-card__body {
    padding: 0 20px !important;
  }

  .queryForm {
    .el-form-item {
      margin: 10px 0 10px 20px;
    }

    .el-form-item:first-child {
      margin-left: 0 !important;
    }

    .el-form-item__label {
      padding-right: 5px;
      color: #555;
    }

    .times {
      .el-form-item__content {
        width: 250px;
      }
    }

    .el-form-item__content {
      min-width: 200px;
    }

    .searchBtnBox {
      display: inline-block;
      margin: 10px 0 10px 20px;
    }
  }

  .pageContent {
    .tabs-list {
      padding-top: 20px;
    }

    .el-tabs__header {
      background: #fff;
    }

    .el-tabs__item {
      border: 1px solid #eee;
      margin: 0;
      border-left: 0;
      background: #fafbfc;
      color: #000;
    }

    .el-tabs__item:first-child {
      margin-left: 20px;
      border-left: 1px solid #eee;
    }

    .is-active {
      border-bottom: 0 !important;
      background: #fff;
      color: #307eff;
    }
  }

  .anjian label {
    padding: 0 !important;
    width: 100px !important;
  }

  .queryForm .el-checkbox {
    margin-right: 10px !important;
    width: auto !important;
  }

  .iszgfc .el-form-item__content {
    width: 120px;
  }
}

/* 上传区域样式 */
.upload-plus {
  width: 100px;
  height: 100px;
  border: 1px dashed #dcdcdc;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  i {
    font-size: 24px;
    color: #999;
  }
}
</style>
